package cup.modules.system.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cup.common.common.Constant;
import cup.common.constant.CommonConstant;
import cup.core.log.exception.ServiceException;
import cup.core.mp.base.BaseServiceImpl;
import cup.modules.system.entity.Dept;
import cup.modules.system.entity.User;
import cup.modules.system.excel.MyUserUploadExcel;
import cup.modules.system.mapper.ParamMapper;
import cup.modules.system.mapper.UserMapper;
import cup.modules.system.service.*;
import cup.modules.system.vo.UserUploadResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : ruoyu
 * @date : 2022/6/27
 */
@Service
public class CqzjLoginServiceImpl extends BaseServiceImpl<UserMapper, User> implements CqzjLoginService {

	private final static String DefaultPostName = "系统新增";
	private final static String DefaultRoleName = "区县用户";

	private static final String TENANTID = "000000";

	private final ParamMapper paramMapper;
	private final IUserService userService;
	private final IPostService iPostService;
	private final IRoleService roleService;
	private final IDeptService iDeptService;

	@Autowired
	public CqzjLoginServiceImpl(ParamMapper paramMapper, IUserService userService,
								IPostService iPostService,
								IRoleService roleService,
								IDeptService iDeptService) {
		this.paramMapper = paramMapper;
		this.userService = userService;
		this.iPostService = iPostService;
		this.roleService = roleService;
		this.iDeptService = iDeptService;
	}

	//todo 后续需要真实对接 这里只是模拟认证授权
	@Override
	public Boolean checkIsExistByEpoint(String tenantId, String username, String password) {
		//提前判断一次是不是真的存在账号输错密码 如果是 则返回true
		Integer tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda()
															 .eq(User::getTenantId, tenantId)
															 .eq(User::getAccount, username)
															 .eq(User::getStatus, CommonConstant.YES_STATUS));

		//todo 后续需要真实对接 这里只是模拟认证授权
		return tenantCount <= 0 && (username.contains("city") || username.contains("district"));
	}

	@Override
	public String initEpointUser(String tenantId, String username, String password, String depId) {
		//拼装数据组成 User
		User user = new User();
		user.setDeptId(depId);
		user.setAccount(username);
		user.setName(username);
		user.setPassword(password);
		String postIds = iPostService.getPostIds(tenantId, DefaultPostName);
		if (StringUtils.isBlank(postIds)) {
			return "未查询到默认岗位,请联系系统管理员!";
		}
		user.setPostId(postIds);
		user.setRealName(username.substring(0, 5));
		//默认新增区县角色
		String roleIds = roleService.getRoleIds(tenantId, DefaultRoleName);
		if (StringUtils.isBlank(roleIds)) {
			return "未查询到默认角色,请联系系统管理员!";
		}
		user.setRoleId(roleIds);
		user.setTenantId(tenantId);
		user.setUserType(1);
		//初始化创建用户账户
		boolean submit = userService.submit(user);
		if (!submit) {
			return "用户初始化失败,请联系管理员";
		}

		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void uploadBaseUser01(List<MyUserUploadExcel> read) {
		UserUploadResultVo userUploadResultVo = new UserUploadResultVo(read.size());
		userUploadResultVo.setAll(read.size());
		String postIds = iPostService.getPostIds(TENANTID, DefaultPostName);
		if (StringUtils.isBlank(postIds)) {
			throw new ServiceException("未查询到默认岗位,请联系系统管理员!");
		}
		String roleIds = roleService.getRoleIds(TENANTID, DefaultRoleName);
		if (StringUtils.isBlank(roleIds)) {
			throw new ServiceException("未查询到默认角色,请联系系统管理员!");
		}
		List<String> phones = new ArrayList<>();
		List<String> regionNames = new ArrayList<>();
		for (MyUserUploadExcel uploadExcel : read) {
			phones.add(uploadExcel.getPhone());
			regionNames.add(uploadExcel.getRegionName());

			//存在相同号吗则跳过
			int count = userService.count(new QueryWrapper<User>()
											  .eq("account", uploadExcel.getPhone())
											  .eq("status", Constant.STATUS_YES)
											  .eq("is_deleted", Constant.DELETE_NO));
			//重复提交的手机号码
			if (count > 0) {
				throw new ServiceException("查询到重复上传的手机号码:[" + uploadExcel.getPhone() + "],请删除后重试提交");
			}
			//查询区域
			Dept dept = iDeptService.getOne(new QueryWrapper<Dept>()
												.eq("dept_name", uploadExcel.getRegionName())
												.eq("is_deleted", Constant.DELETE_NO));

			if (null == dept) {
				throw new ServiceException("未查询到区县名称:[" + uploadExcel.getRegionName() + "],您的手机号码[" + uploadExcel.getPhone() + "],请确认修改后再提交");
			}

		}


		List<User> userList = userService.getBaseMapper().selectList(new QueryWrapper<User>()
																		 .in("account", phones)
																		 .eq("status", Constant.STATUS_YES)
																		 .eq("is_deleted", Constant.DELETE_NO));
		if (userList.size() > 0) {
			//存在相同号吗则跳过
			throw new ServiceException("查询到重复上传的手机号码:[" + userList.get(0).getPhone() + "],请删除后重试提交");
		}
		//查询区域
		List<Dept> depts = iDeptService.getBaseMapper().selectList(new QueryWrapper<Dept>()
																	   .in("dept_name", regionNames)
																	   .eq("is_deleted", Constant.DELETE_NO));
		List<String> copyRegionNames = new ArrayList<>();
		BeanUtils.copyProperties(regionNames, copyRegionNames);
		for (String regionName : regionNames) {
			for (Dept dept : depts) {
				if (regionNames.equals(dept.getDeptName())) {
					copyRegionNames.remove(regionName);
				}
			}
		}

		if (copyRegionNames.size() > 0) {
			MyUserUploadExcel excel = new MyUserUploadExcel();
			for (MyUserUploadExcel uploadExcel : read) {
				if (copyRegionNames.get(0).equals(uploadExcel.getRegionName())) {
					excel = uploadExcel;
				}
			}
			throw new ServiceException("未查询到区县名称:[" + copyRegionNames.get(0) + "],您的手机号码[" + excel.getPhone() + "],请确认修改后再提交");
		}
	}
}
